﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameController : MonoBehaviour 
{
    public GameObject hazard;
    public GameObject[] Hazards;

    public Vector3 spawnValues;

    public int HazardCount;

    public float SpawnWait;

    public float StartWait;

    public float WaveWait;

    public Text ScoreText;
    private int score;

    public Text RestartText;
    public Text GameOverText;

    private bool _GameOver = false;
    private bool _Restart = false;

    void Start()
    {
        _GameOver = false;
        _Restart = false;

        score = 0;
        UpdateScore();
        StartCoroutine(SpawnWaves());

        RestartText.text = "";
        GameOverText.text = "";
    }

    void Update()
    {
        if(_Restart == true)
        {
            if(Input.GetKeyDown (KeyCode.R))
            {
                Application.LoadLevel(Application.loadedLevel);
            }
        }
    }
    
	IEnumerator SpawnWaves()
    {
        yield return new WaitForSeconds(StartWait);

        while (true)
        {
            for (int i = 0; i < HazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);

                Quaternion spawnRotation = Quaternion.identity;

                Instantiate(Hazards[Random.Range(0, Hazards.Length)], spawnPosition, spawnRotation);

                yield return new WaitForSeconds(SpawnWait);
            }

            yield return new WaitForSeconds(WaveWait);

            if (_GameOver == true)
                break;
            }
    }

    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore();
    }

    void UpdateScore()
    {
        ScoreText.text = "Score: " + score.ToString();
    }

    public void GameOver()
    {
        GameOverText.text = "Game Over!";
        _GameOver = true;

        if (_GameOver == true)
        {
            RestartText.text = "Press 'R' for Restart";
            _Restart = true;
            return;
        }
    }

    public bool CheckState()
    {
        if (_GameOver == true)
            return true;
        else
            return false;
    }
}
